using System;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UI.BankingPanel.Data;

/// <summary>
/// 银行数据持久化管理器
/// 专门处理BankingData的保存和加载
/// </summary>
public static class BankingDataPersistence
{
    private static readonly string SavePath = Path.Combine(Application.persistentDataPath, "banking_data.json");
    
    /// <summary>
    /// 可序列化的银行数据容器
    /// </summary>
    [Serializable]
    public class SerializableBankingData
    {
        [Header("基础设置")]
        public float averageBetAmount = 206f;
        public float maxLossLimit = 4000f;
        public float odds = 47f;
        
        [Header("总体数据")]
        public float totalBetAmount;
        public float totalSelfBetAmount;
        public float totalReportAmount;
        
        [Header("号码数据")]
        public List<SerializableNumberBetData> numberBetList = new List<SerializableNumberBetData>();
        
        /// <summary>
        /// 从BankingData转换
        /// </summary>
        public static SerializableBankingData FromBankingData(BankingData bankingData)
        {
            var serializable = new SerializableBankingData();
            serializable.averageBetAmount = bankingData.averageBetAmount;
            serializable.maxLossLimit = bankingData.maxLossLimit;
            serializable.odds = bankingData.odds;
            serializable.totalBetAmount = bankingData.totalBetAmount;
            serializable.totalSelfBetAmount = bankingData.totalSelfBetAmount;
            serializable.totalReportAmount = bankingData.totalReportAmount;
            
            serializable.numberBetList.Clear();
            foreach (var numberData in bankingData.numberBetList)
            {
                serializable.numberBetList.Add(SerializableNumberBetData.FromNumberBetData(numberData));
            }
            
            return serializable;
        }
        
        /// <summary>
        /// 转换为BankingData
        /// </summary>
        public BankingData ToBankingData()
        {
            var bankingData = new BankingData();
            bankingData.averageBetAmount = this.averageBetAmount;
            bankingData.maxLossLimit = this.maxLossLimit;
            bankingData.odds = this.odds;
            bankingData.totalBetAmount = this.totalBetAmount;
            bankingData.totalSelfBetAmount = this.totalSelfBetAmount;
            bankingData.totalReportAmount = this.totalReportAmount;
            
            // 更新号码数据
            for (int i = 0; i < this.numberBetList.Count && i < bankingData.numberBetList.Count; i++)
            {
                var serializableData = this.numberBetList[i];
                var bankingNumberData = bankingData.numberBetList[i];
                
                bankingNumberData.number = serializableData.number;
                bankingNumberData.totalBetAmount = serializableData.totalBetAmount;
                bankingNumberData.selfBetAmount = serializableData.selfBetAmount;
                bankingNumberData.reportAmount = serializableData.reportAmount;
                bankingNumberData.riskValue = serializableData.riskValue;
                bankingNumberData.originalEatCode = serializableData.originalEatCode;
            }
            
            // 重新计算风险值
            bankingData.RecalculateAllRiskValues();
            
            return bankingData;
        }
    }
    
    /// <summary>
    /// 可序列化的号码押注数据
    /// </summary>
    [Serializable]
    public class SerializableNumberBetData
    {
        public int number;
        public float totalBetAmount;
        public float selfBetAmount;
        public float reportAmount;
        public float riskValue;
        public float originalEatCode;
        
        public static SerializableNumberBetData FromNumberBetData(NumberBetData numberBetData)
        {
            return new SerializableNumberBetData
            {
                number = numberBetData.number,
                totalBetAmount = numberBetData.totalBetAmount,
                selfBetAmount = numberBetData.selfBetAmount,
                reportAmount = numberBetData.reportAmount,
                riskValue = numberBetData.riskValue,
                originalEatCode = numberBetData.originalEatCode
            };
        }
    }
    
    /// <summary>
    /// 保存银行数据到文件
    /// </summary>
    /// <param name="bankingData">要保存的银行数据</param>
    public static void SaveBankingData(BankingData bankingData)
    {
        try
        {
            if (bankingData == null)
            {
                Debug.LogError("[BankingDataPersistence] 银行数据为空，无法保存");
                return;
            }
            
            // 转换为可序列化格式
            var serializableData = SerializableBankingData.FromBankingData(bankingData);
            
            // 序列化为JSON
            string json = JsonUtility.ToJson(serializableData, true);
            
            // 写入文件
            File.WriteAllText(SavePath, json);
            
            Debug.Log($"[BankingDataPersistence] 银行数据已保存到: {SavePath}");
        }
        catch (Exception ex)
        {
            Debug.LogError($"[BankingDataPersistence] 保存银行数据失败: {ex.Message}\n{ex.StackTrace}");
        }
    }
    
    /// <summary>
    /// 从文件加载银行数据
    /// </summary>
    /// <returns>加载的银行数据，如果失败则返回新的默认数据</returns>
    public static BankingData LoadBankingData()
    {
        try
        {
            if (File.Exists(SavePath))
            {
                // 读取文件
                string json = File.ReadAllText(SavePath);
                
                // 反序列化
                var serializableData = JsonUtility.FromJson<SerializableBankingData>(json);
                
                if (serializableData != null)
                {
                    Debug.Log($"[BankingDataPersistence] 银行数据已从文件加载: {SavePath}");
                    return serializableData.ToBankingData();
                }
                else
                {
                    Debug.LogWarning("[BankingDataPersistence] 加载的银行数据为空，使用默认数据");
                }
            }
            else
            {
                Debug.Log("[BankingDataPersistence] 未找到银行数据保存文件，使用默认数据");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"[BankingDataPersistence] 加载银行数据失败: {ex.Message}\n{ex.StackTrace}");
        }
        
        // 返回默认数据
        return new BankingData();
    }
    
    /// <summary>
    /// 删除保存的银行数据文件
    /// </summary>
    public static void DeleteBankingData()
    {
        try
        {
            if (File.Exists(SavePath))
            {
                File.Delete(SavePath);
                Debug.Log("[BankingDataPersistence] 银行数据文件已删除");
            }
            else
            {
                Debug.Log("[BankingDataPersistence] 银行数据文件不存在");
            }
        }
        catch (Exception ex)
        {
            Debug.LogError($"[BankingDataPersistence] 删除银行数据文件失败: {ex.Message}");
        }
    }
    
    /// <summary>
    /// 检查是否存在保存的银行数据
    /// </summary>
    /// <returns>如果存在保存文件返回true</returns>
    public static bool HasSavedBankingData()
    {
        return File.Exists(SavePath);
    }
    
    /// <summary>
    /// 获取保存文件路径
    /// </summary>
    /// <returns>保存文件的完整路径</returns>
    public static string GetSavePath()
    {
        return SavePath;
    }
    
    /// <summary>
    /// 自动保存银行数据（带延迟，避免频繁保存）
    /// </summary>
    /// <param name="bankingData">要保存的银行数据</param>
    /// <param name="delay">延迟时间（秒）</param>
    public static void AutoSaveBankingData(BankingData bankingData, float delay = 1f)
    {
        // 取消之前的自动保存
        if (_autoSaveCoroutine != null)
        {
            if (_coroutineRunner != null)
            {
                _coroutineRunner.StopCoroutine(_autoSaveCoroutine);
            }
        }
        
        // 启动新的自动保存
        if (_coroutineRunner != null)
        {
            _autoSaveCoroutine = _coroutineRunner.StartCoroutine(AutoSaveCoroutine(bankingData, delay));
        }
        else
        {
            // 如果没有协程运行器，直接保存
            SaveBankingData(bankingData);
        }
    }
    
    private static MonoBehaviour _coroutineRunner;
    private static UnityEngine.Coroutine _autoSaveCoroutine;
    
    /// <summary>
    /// 设置协程运行器（用于自动保存功能）
    /// </summary>
    /// <param name="runner">MonoBehaviour实例</param>
    public static void SetCoroutineRunner(MonoBehaviour runner)
    {
        _coroutineRunner = runner;
    }
    
    /// <summary>
    /// 自动保存协程
    /// </summary>
    private static System.Collections.IEnumerator AutoSaveCoroutine(BankingData bankingData, float delay)
    {
        yield return new UnityEngine.WaitForSeconds(delay);
        SaveBankingData(bankingData);
        _autoSaveCoroutine = null;
    }
} 